from PyQt4.QtCore import *
from PyQt4.QtGui import *

from ops import InputItem, CancelException
from ops import StringT, NumberT
import properties

import os.path

import Raster

from rasterFile import Ui_RasterFile
class RasterFile(InputItem):
    name = "RasterFile"
    def __init__(self,x,y):
        InputItem.__init__(self,x,y,[],["Out"],"Raster File")
        self.propsDialog = Ui_RasterFile()
        self.setToolTip("Raster read from file")
        self.outputs[0].value = None
        self.props = {'filePath': ""}
        if not self.properties():
            raise CancelException
    def displayText(self):
        if not hasattr(self,"props"):
            return "Raster file"
        return os.path.split(str(self.props['filePath']))[1]
    def propDef(self):
        return {'filePath': StringT}
    def vnames(self):
        return ["filePath",]

    def properties(self):
        self.d = properties.dialog(self.propsDialog)
        QObject.connect(self.d.ui.fileButton,SIGNAL("clicked()"),self.fileButtonClicked)
        # set dialog from object's values
        self.setDialogValues(self.d.ui)
        if properties.show(self.d):
            command = CommandEditRasterFile(self,self.getDialogValues(self.d.ui))
            if self.scene():
                self.scene().undoStack.push(command)
            else:
                command.redo()
            return True
        else:
            return False
        
    def fileButtonClicked(self):
        fp = QFileDialog.getOpenFileName(None, "Choose a raster file",
                                      self.d.ui.filePath.text())
        if fp:
            self.d.ui.filePath.setText(fp)
            

    def process(self):
        self.outputs[0].value=Raster.fromFile(self.props['filePath'])

class CommandEditRasterFile(QUndoCommand):
    def __init__(self,item,newValues):
        QUndoCommand.__init__(self,"Edit raster file")
        self.newValues = newValues
        self.item = item
        self.oldValues = item.props

    def redo(self):
        item = self.item
        item.props = self.newValues
        #item.outputs[0].value = self.newValues
        self.update()

    def undo(self):
        item = self.item
        item.props = self.oldValues
        self.update()

    def update(self):
        item = self.item
        item.setPlainText(item.displayText())
        item.locateOutputHandles()
        item.update(item.boundingRect())
